import { ref, nextTick } from "vue";
import { renderDelta } from "@/utils/mdStream";

export function useMdStream() {
  const html = ref("");
  const raw = ref("");

  // 外部每收到一次 delta 就调用 append
  const append = (delta: string) => {
    raw.value += delta;
    html.value = renderDelta(raw.value, html.value);
    // 等 DOM 更新后滚动到底部
    nextTick(() => scrollToBottom());
  };

  const reset = () => {
    raw.value = "";
    html.value = "";
  };

  return { html, append, reset };
}

function scrollToBottom() {
  const el = document.getElementById("md-container");
  if (el) {
    window.scrollTo({ top: el.scrollHeight });
    //   console.log("scroll");
  }
}
